﻿
using Red.Core;
using System;
using System.Collections.Generic;

namespace Red.Controls.DataDriven
{
    /// <summary>
    ///     Defines a control that maps to an Interop type.
    /// </summary>
    [AttributeUsage( AttributeTargets.Class )]
    public class InteropControlAttribute : MappableAttribute
    {
        private static readonly Dictionary< string, Type > _controlMap = new Dictionary<string, Type>();
        private static bool _rebuildMapScheduled = true;

        public string[] InteropTypes { get; set; }

        public static Dictionary<string, Type> ControlMap
        {
            get
            {
                if ( _rebuildMapScheduled )
                {
                    RebuildMap();
                    _rebuildMapScheduled = false;
                }
                return _controlMap;
            }
        }

        public InteropControlAttribute( params string[] interopTypes )
        {
            _rebuildMapScheduled = true;
            InteropTypes = interopTypes;
        }

        private static void RebuildMap()
        {
            _controlMap.Clear();
            ClassMap.RegisterClassesWithAtrributeListener<InteropControlAttribute>(
                ( Type type, InteropControlAttribute attr ) =>
                {
                    foreach ( string interopType in attr.InteropTypes )
                        _controlMap.Add( interopType, type );
                } );
        }
    }
}
